<template>
  <div class="tea-details h-100% w-100%">
    <swiper v-if="bannerList" autoplay circular class="h-460rpx" :style="{ paddingTop: `${searchBarTop}px` }">
      <swiper-item v-for="swip in bannerList" class="overflow-hidden">
        <image
          :src="swip"
          class="pointer-events-none h-460rpx w-full"
          mode="scaleToFill"
        />
      </swiper-item>
    </swiper>
    <div class="content pl-32rpx pr-32rpx pt-44rpx">
      <div class="mb-32rpx flex items-center">
        <span class="text-32rpx font-600">{{ goodsDetail.productName }}</span>
        <image
          :src="`${cdnUrl}/svgicons/teaDetails/leaf.svg${imgVersion}`"
          mode="scaleToFill"
          class="h-48rpx w-48rpx"
        />
      </div>
      <!-- 单饮品加小料 -->
      <div v-if="singleTea">
        <div class="title mb-32rpx box-border rounded-32rpx bg-hex-ffffff p-32rpx">
          <div class="tag">
            <!-- 必选 -->
            <div v-for="(item, index) in tempOptionsList.attributeList" class="mb-34rpxt">
              <div class="mb-15rpx w-20% text-28rpx font-bold text-hex-333">{{ item.name }}</div>
              <div class="flex flex-wrap items-center">
                <div
                  v-for="(tag, i) in item.childList"
                  :class="item.val.name===tag.name?'text-hex-ABCD03 border-2rpx border-hex-ABCD03 border-solid':'text-hex-999'"
                  class="mb-20rpx mr-24rpx h-44rpx rounded-8rpx bg-hex-f5f5f5 px-24rpx text-24rpx leading-44rpx"
                  @click="selectOption(item, tag)">
                  {{ tag.name }}
                </div>
              </div>
            </div>
            <!-- 可选 -->
            <div
              v-if="optionalList?.length>0"
              class="mb-34rpx">
              <div class="mb-15rpx w-20% text-28rpx font-bold text-hex-333">小料</div>
              <div class="flex flex-wrap items-center">
                <div
                  v-for="(item, index) in optionalList"
                  :class="item.isSelect?'text-hex-ABCD03 border-2rpx border-solid border-hex-ABCD03 ':'border-hex-f5f5f5 border-solid border-2rpx  text-hex-999'"
                  class="mb-20rpx mr-24rpx h-44rpx rounded-8rpx bg-hex-f5f5f5 px-24rpx text-24rpx leading-44rpx"
                  @click="selectChips(item)"
                >
                  {{ item.productName }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="relative mt-52rpx">
          <div class="hot relative box-border rounded-20rpx bg-hex-fff p-24rpx">
            <span class="title text-28rpx">
              <image
                :src="`${cdnUrl}/svgicons/search/emoji.svg${imgVersion}`"
                mode="scaleToFill"
                class="h-28rpx w-28rpx"
              />
              <span class="z-99">夏日推荐榜</span>
            </span>
            <div
              v-for="item in items"
              class="hot-item z-999 mt-36rpx h-180rpx flex pr-25rpx"
              @click="goDetail(item.unionFlag, item.id)">
              <div 
                class="relative mr-3% mt-24rpx h-180rpx w-180rpx overflow-hidden rounded-16rpx">
                <image
                  class="absolute left-50% top-50% h-180rpx w-180rpx rounded-16rpx"
                  style="transform: translate(-50%, -50%);" :src="item.productImage" mode="aspectFill" />
              </div>
              <div class="relative ml-20rpx h-100% flex-1">
                <div>
                  <div class="text-28rpx font-600 leading-38rpx">{{ item.productName }}</div>
                  <div class="mt-16rpx flex items-center text-24rpx text-hex-7C8699">
                    <div>{{ item.productIntro }}</div>
                  </div>
                </div>
                <div class="absolute bottom-0 w-100%">
                  <div class="flex items-center">
                    <div class="flex-1 text-28rpx text-hex-333">￥{{ item.productPrice }}</div>
                    <image
                      :src="`${cdnUrl}/svgicons/userComment/add.svg${imgVersion}`"
                      mode="scaleToFill"
                      class="mt-5rpx h-50rpx w-50rpx"
                    />
                  </div>
                </div>
              </div>
            </div>
            <div
              v-if="moreShow"
              class="bgblur absolute bottom-0 left-0 right-0 h-100rpx w-100% flex items-center justify-center rounded-b-24rpx bg-[rgba(255,255,255,0.67)]"
              @click="getAllRecommentList">
              <image
                :src="`${cdnUrl}/imgs/tea/downMore.png${imgVersion}`"
                mode="scaleToFill"
                class="h-32rpx w-32rpx"
              />
              <span class="text-24rpx text-hex-7C8699">展开全部</span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="!singleTea">
        <!-- 套餐 -->
        <div v-for="item in tempOptionsList" class="title mb-32rpx box-border rounded-32rpx bg-hex-ffffff p-32rpx">
          <div class="mb-32rpx h-256rpx w-256rpx flex flex-col items-center justify-center rounded-26rpx bg-hex-F5F5F5">
            <div class="relative min-h-152rpx flex">
              <image
                :src="item.productImage"
                mode="scaleToFill"
                class="z-9 h-152rpx w-104rpx"
              />
              <div class="absolute bottom-0 h-126rpx w-126rpx rounded-50% bg-hex-CFEDE6" />
            </div>
            <div class="mt-8rpx box-border pl-16rpx text-28rpx font-bold text-hex-333333">
              <div class="mb-4rpx">{{ item.productName }}</div>
            <!-- <div class="font-numberFont">¥{{ item.price }}</div>  -->
            </div>
          </div>
          <!-- 必选 -->
          <div class="tag">
            <div v-for="(itm, index) in item.attributeList">
              <div v-if="itm.necessaryFlag !== 1" class="mb-34rpx">
                <div class="mb-15rpx w-20% text-28rpx font-bold text-hex-333">{{ itm.name }}</div>
                <div class="flex flex-wrap items-center">
                  <div
                    v-for="(tag, i) in itm.childList"
                    :class="itm.val.name===tag.name?'text-hex-ABCD03 border-2rpx border-hex-ABCD03 border-solid':'text-hex-999'"
                    class="mb-20rpx mr-24rpx h-44rpx rounded-8rpx bg-hex-f5f5f5 px-24rpx text-24rpx leading-44rpx"
                    @click="doubleSelectOption(item, itm, tag)">
                    {{ tag.name }}
                  </div>
                </div>
              </div>
            </div>
            <!-- 可选 -->
            <div
              v-if="item.blendList.length>0"
              class="mb-34rpx">
              <div class="mb-15rpx w-20% text-28rpx font-bold text-hex-333">小料</div>
              <div class="flex flex-wrap items-center">
                <div
                  v-for="(itm, index) in item.blendList"
                  :class="itm.isSelect?'text-hex-ABCD03 border-2rpx border-hex-ABCD03 border-solid':'text-hex-999'"
                  class="mr-24rpx h-44rpx rounded-8rpx bg-hex-f5f5f5 px-24rpx text-24rpx leading-44rpx"
                  @click="doubleSelectChip(itm)"
                >
                  {{ itm.productName }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 图文详情 -->
      <div class="mt-32rpx box-border rounded-24rpx bg-hex-fff px-32rpx">
        <text class="font-28rpx my-32rpx inline-block text-24rpx font-600 text-hex-000">商品详情</text>
        <div v-if="goodsDetailContent" class="mb-32rpx">
          <!-- <image
            v-for="item in goodsDetailContent"
            :src="item"
            class="w-100% rounded-24rpx"
            mode="widthFix"
          />
          <div
            v-if="goodsDetail"
            class="font-28rpx my-32rpx inline-block text-24rpx font-600 text-hex-000">{{ goodsDetail.productIntro }}</div> -->
          <rich-text :nodes="goodsDetailContent" /></div>
      </div>
      <div class="h-220rpx" />
    </div>
    <div class="absolute top-0 w-100%" :style="{ paddingTop: `${topHight}px` }">
      <uni-nav-bar left-icon="left" :border="false" background-color="transparent" color="#ABCD03" @clickLeft="goback" />
    </div>
    <div class="fixed bottom-0 left-0 right-0 z-99 box-border rounded-t-32rpx bg-hex-fff p-32rpx pb-50rpx">
      <div class="mb-16rpx flex items-center justify-between">
        <div>
          <div class="mb-10rpx">
            <text class="font-numberFont mr-10rpx text-28rpx text-hex-E36043">￥{{ finallPrice }}</text>
            <text class="text-24rpx text-hex-999" style="text-decoration: line-through;">￥{{ goodsDetail.cost }}</text>
          </div>
          <div class="text-24rpx text-hex-7C8699">{{ selectName }}</div>
        </div>
        <div class="flex items-center">
          <image
            :src="`${cdnUrl}/svgicons/userComment/down.svg${imgVersion}`"
            mode="scaleToFill"
            class="mt-5rpx h-50rpx w-50rpx"
            @click="reduceShop"
          />
          <div class="ml-24rpx mr-24rpx">{{ shopnum }}</div>
          <image
            :src="`${cdnUrl}/svgicons/userComment/add.svg${imgVersion}`"
            mode="scaleToFill"
            class="mt-5rpx h-50rpx w-50rpx"
            @click="addShop"
          />
        </div>
      </div>
      <div class="flex justify-between text-28rpx">
        <!-- <div class="h-72rpx w-328rpx border-2rpx border-hex-ABCD03 rounded-46rpx border-solid text-center leading-72rpx text-hex-ABCD03" @click="navTo('/pages-tea/comfirmOrder')">立即购买</div> -->
        <div class="btn-theme-bg h-72rpx w-100% rounded-46rpx text-center leading-72rpx text-hex-fff" @click="joinGoodsCar">加入购物车</div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useAddressStore } from '@/stores/address'

let topHight = $ref(0)
let productId: any = $ref('')
let addressStores: any = useAddressStore()
const userStores = useUserStore()
let searchBarTop: any = $ref('24')

onLoad((options) => {
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top + 35
  // #ifdef MP-WEIXIN
  const { capsuleTop } = useCapsulePosition()
  topHight = capsuleTop.value
  // #endif
  if (options) {
    productId = options.productId
  }
})
let items: any = $ref([])
let tagList: any = $ref([])
//商品数量
let shopnum = $ref(1)
//商品减
const reduceShop = () => {
  if (shopnum > 1) {
    shopnum = shopnum - 1
  }
}
//商品添加
const addShop = () => {
  if (shopnum < 20) {
    shopnum = shopnum + 1
    return
  }
  uni.showToast({
    title: '超过最大加购数量',
    icon: 'none',
  })
}
let initTotalPrice: any = $ref('')
let finallPrice: any = $ref('')
let priceList: any = $ref([])
let attributesList: any = $ref([]) //用户所选的属性列表类似杯型温度糖分等
let childrenSkusList: any = $ref([])

const selectOption = (item, tag) => {
  item.val = tag
  // console.log(tempOptionsList, 'tempOptionsList')
  attributesList = []
  let tempNameList: any = []
  tempNameList[0] = goodsDetail.productName
  tempOptionsList.attributeList.forEach((itm) => {
    attributesList.push({
      'attributeId': itm.id,
      'attributeValueIds': [itm.val.id],
    })
    tempNameList.push(itm.val.name)
  })
  optionalList.forEach((optionItem) => {
    if (optionItem.isSelect) {
      tempNameList.push(optionItem.skuList[0].productSkuName)
    }
  })
  selectName = tempNameList.join('+')
  let necessaryFlagList: any = []
  necessaryFlagList = tempOptionsList.attributeList.filter((itm) => {
    return itm.necessaryFlag === 1
  })
  let filterskuList: any = []
  filterskuList = tempOptionsList.skuList.filter((itm) => {
    return necessaryFlagList[0].val.id === itm.specs[0].v_id
  })
  initTotalPrice = filterskuList[0].productSkuPrice
  priceList[0] = initTotalPrice
  finallPrice = priceList.reduce((pre, cur) => {
    return Number(pre) + Number(cur)
  })
  nessOptionsList.attributes = attributesList
  nessOptionsList.productId = tempOptionsList.childProductId
  nessOptionsList.skuId = filterskuList[0].id
  childrenSkusList[0] = nessOptionsList
}

// 套餐选择属性值
const doubleSelectOption = (firstOption, item, tag) => {
  item.val = tag
  // console.log(tempOptionsList, '点击属性值选择的时候的tempOptionsList')
  childrenSkusList = []
  priceList = []
  priceList.push(initTotalPrice)
  let tempAttributesList: any = []
  tempOptionsList.forEach((teaItem) => {
    tempAttributesList = []
    teaItem.attributeList.forEach((item) => {
      tempAttributesList.push({ 'attributeId': item.id, 'attributeValueIds': [item.val.id] })
    })
    childrenSkusList.push({
      'attributes': tempAttributesList,
      'productId': teaItem.childProductId,
      'skuId': teaItem.skuList[0].id,
    })
    teaItem.blendList.forEach((perBlend) => {
      if (perBlend.isSelect) {
        priceList.push(perBlend.skuList[0].productSkuPrice)
        childrenSkusList.push({
          'attributes': [],
          'productId': perBlend.childProductId,
          'skuId': perBlend.skuList[0].id,
        })
      }
    })
  })
  finallPrice = priceList.reduce((pre, cur) => {
    return Number(pre) + Number(cur)
  })
}
const doubleSelectChip = (item) => {
  if (item.isSelect) {
    item.isSelect = !item.isSelect
  } else {
    item.isSelect = true
  }
  priceList = []
  priceList.push(initTotalPrice)
  // console.log(tempOptionsList, 'tempOptionsList')
  childrenSkusList = []
  let tempAttributesList: any = []
  tempOptionsList.forEach((per) => {
    tempAttributesList = []
    per.attributeList.forEach((item) => {
      tempAttributesList.push({ 'attributeId': item.id, 'attributeValueIds': [item.val.id] })
    })
    childrenSkusList.push({
      'attributes': tempAttributesList,
      'productId': per.childProductId,
      'skuId': per.skuList[0].id,
    })
    per.blendList.forEach((perBlend) => {
      if (perBlend.isSelect) {
        priceList.push(perBlend.skuList[0].productSkuPrice)
        childrenSkusList.push({
          'attributes': [],
          'productId': perBlend.childProductId,
          'skuId': perBlend.skuList[0].id,
        })
      }
    })
  })
  finallPrice = priceList.reduce((pre, cur) => {
    return Number(pre) + Number(cur)
  })
}

// 单饮品加小料选择小料的事件
const selectChips = (item) => {
  if (item.isSelect) {
    item.isSelect = !item.isSelect
  } else {
    item.isSelect = true
  }
  priceList = []
  priceList.push(initTotalPrice)
  childrenSkusList = []
  childrenSkusList[0] = nessOptionsList
  let tempNameList: any = []
  tempNameList[0] = goodsDetail.productName
  optionalList.forEach((itm) => {
    if (itm.isSelect) {
      priceList.push(itm.skuList[0].productSkuPrice)
      childrenSkusList.push({
        'attributes': [],
        'productId': itm.childProductId,
        'skuId': itm.skuList[0].id,
      })
      tempNameList.push(itm.skuList[0].productSkuName)
    }
  })
  finallPrice = priceList.reduce((pre, cur) => {
    return Number(pre) + Number(cur)
  })
  tempOptionsList.attributeList.forEach((itm) => {
    tempNameList.push(itm.val.name)
  })
  selectName = tempNameList.join('+')

}

let goodsDetail: any = $ref({})
let goodsDetailContent: any = $ref([])
let recommendList: any = $ref([])
let moreShow: any = $ref(false)
let tempOptionsList: any = $ref([])
let optionalList: any = $ref([]) //可选
let skuList: any = $ref([])
let singleTea: any = $ref(false)
let nessOptionsList: any = $ref({})
let bannerList: any = $ref([])
let selectName: any = $ref('')
// 获取商品详情
const getGoodsDetail = async () => {
  const reqData = {
    method: 'post',
    data: {
      'productId': productId,
      'storeId': addressStores.selectStores.id,
      appType: 2,
    },
    headers: {
      AppType: 2,
      // UserId: 1,
      UserId: userStores.user.id,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/product/product/detail', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  let tempList = data.result.productElementList
  goodsDetail = data.result
  bannerList = goodsDetail?.productBannerImage.split(',')
  // 必选
  tempOptionsList = tempList.filter((item) => {
    return item.optionFlag === 1
  })
  if (tempOptionsList.length === 1) {
    tempOptionsList = tempOptionsList[0]
    singleTea = true
    // console.log(tempOptionsList)
    let tempNameList: any = []
    tempNameList[0] = goodsDetail.productName
    tempOptionsList?.attributeList.forEach((item) => {
      item.val = item.childList[0]
      tempNameList.push(item.val.name)
    })
    selectName = tempNameList.join('+')
    tempOptionsList?.skuList.forEach((itm) => {
      itm.specs = JSON.parse(itm.specs)
    })
    attributesList = []
    tempOptionsList.attributeList.forEach((itm) => {
      attributesList.push({
        'attributeId': itm.id,
        'attributeValueIds': [itm.val.id],
      })
    })
    let necessaryFlagList: any = []
    necessaryFlagList = tempOptionsList.attributeList.filter((itm) => {
      return itm.necessaryFlag === 1
    })
    let filterskuList: any = []
    filterskuList = tempOptionsList.skuList.filter((itm) => {
      return necessaryFlagList[0].val.id === itm.specs[0].v_id
    })
    initTotalPrice = filterskuList[0].productSkuPrice
    nessOptionsList.attributes = attributesList
    nessOptionsList.productId = tempOptionsList.childProductId
    nessOptionsList.skuId = filterskuList[0].id
    finallPrice = initTotalPrice
    // console.log(nessOptionsList, 'nessOptionsList')
    childrenSkusList.push(nessOptionsList)
  } else {
    singleTea = false
    let canOptionSelectList: any = []
    canOptionSelectList = tempList.filter((item) => {
      return item.optionFlag === 0
    })
    let tempNameList: any = []
    tempOptionsList.forEach((teaItem) => {
      teaItem.blendList = []
      canOptionSelectList.forEach((skuItem) => {
        if (teaItem.childProductId === skuItem.bindChildProductId) {
          teaItem.blendList.push(skuItem)
        }
      })
      let tempAttributesList: any = []
      teaItem.attributeList.forEach((item) => {
        item.val = item.childList[0]
        tempAttributesList.push({ 'attributeId': item.id, 'attributeValueIds': [item.val.id] })
      })
      childrenSkusList.push({
        'attributes': tempAttributesList,
        'productId': teaItem.childProductId,
        'skuId': teaItem.skuList[0].id,
      })
      tempNameList.push(teaItem.productName)

    })
    selectName = tempNameList.join('+')
    initTotalPrice = goodsDetail.productPrice
    finallPrice = initTotalPrice
  }
  // 可选
  optionalList = tempList.filter((item) => {
    return item.optionFlag === 0
  })
  tagList.forEach((item: any) => {
    item.val = item.childList[0]
  })
  // goodsDetailContent = goodsDetail?.productDetailImage.split(',')
  goodsDetailContent = goodsDetail?.productDetailImage.replace(/style=""/g, 'style="max-width:100% !important;display:block;"')
  recommendList = goodsDetail?.recommendList
  if (recommendList.length > 3) {
    items = recommendList.splice(0, 3)
    moreShow = true
    return
  }
  items = recommendList
}



const goDetail = (type, id) => {
  if (type === 1) {
    navTo(`/pages-tea/doubleDetails?productId=${id}`)
  } else {
    navTo(`/pages-tea/details?productId=${id}`)
  }
}
const getAllRecommentList = () => {
  items = recommendList
  moreShow = false
}

// 加入购物车
const joinGoodsCar = async () => {
  const reqData = {
    method: 'post',
    data: {
      'detailDTO': {
        'amount': shopnum,
        'childrenSkus': childrenSkusList,
        'productId': productId,
        'isJoinedActivity': false,
      },
      'trolleyType': 2,
      'userId': userStores.user.id,
    },
    headers: { UserId: userStores.user.id },
  }
  uni.showLoading({ title: '加入中' })
  const { data, status, error } = await Fetch('/qqyapi/order/trolley/addItem', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    uni.hideLoading()
    uni.showToast({
      title: '商品已加入购物车',
      icon: 'none',
    })
    setTimeout(() => {
      uni.switchTab({ url: '/pages/index' })
      uni.$emit('handelEvent')
    }, 600)
  }

}


onMounted(() => {
  getGoodsDetail()
})

//返回上一级
const goback = () => {
  uni.navigateBack({
    delta: 1,
  })
}
</script>

<style lang="scss">
.tea-details{
  background: linear-gradient(180deg, #FFF 0%, #f5f5f5 100%);

  .activeClass{
    background-color: #EDFDF8;
    border: 1rpx solid #ABCD03 ;
  }

  .hot{
    background-image: url('https://qqy-1254346585.cos.ap-nanjing.myqcloud.com/qqy/svgicons/search/searchbg.svg');
    background-size: 100%;
    background-repeat: no-repeat;
  }

  .bgblur{
    backdrop-filter: blur(8rpx);
  }

  // ::v-deep .uni-icons{
  //   color: #18a786 !important;
  // }

  .font-numberFont{
    font-family:'DingTalk JinBuTi';
  }

  .scroll-view-item {
    height: 300rpx;
  }

  .scrolldemo{
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    overflow-x: hidden;
  }

  ::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }

  .tagClass::after{
    position: absolute;
    content: '';
    height:14rpx;
    width:2rpx;
    top: 10rpx;
    right: -10rpx;
    background-color: #7c8699;
  }

  .tagClass:last-child::after{
    width: 0rpx;
    height:0rpx;
  }
}

</style>
